package indi.kenny;

import cn.hutool.core.util.HashUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import redis.clients.jedis.Jedis;

/**
 * 布隆过滤器的简单实现
 * 功能：能判断某样东西一定不存在或者可能存在
 * 特点：高效插入和查询、占有空间少
 */
public class Main {
    private static final String BLOOM_FILTER = "bloom_filter";
    private static int prime = 100000000;  //一亿bit
    private static Jedis jedis = RedisDS.create().getJedis();


    public static void main(String[] args) {
        String[] url = new String[]{"www.baidu.com", "www.sina.com", "ww.jjk.com"};
        for (String s : url) {
            sign(s);
        }
        for (String s : url) {
            System.out.println(exists(s));
        }

    }

    /**
     * 三次hash取值，存入redis对应的bit
     *
     * @param key
     */
    public static void sign(String key) {
        int hash1 = HashUtil.additiveHash(key, prime);
        int hash2 = HashUtil.sdbmHash(key) % prime;
        int hash3 = HashUtil.dekHash(key) % prime;
        jedis.setbit(BLOOM_FILTER, hash1, true);
        jedis.setbit(BLOOM_FILTER, hash2, true);
        jedis.setbit(BLOOM_FILTER, hash3, true);
    }

    /**
     * 三次hash取值，反向查询对应的bit是否均为true
     *
     * @param key
     * @return
     */
    public static boolean exists(String key) {
        int hash1 = HashUtil.additiveHash(key, prime);
        int hash2 = HashUtil.sdbmHash(key) % prime;
        int hash3 = HashUtil.dekHash(key) % prime;
        return jedis.getbit(BLOOM_FILTER, hash1) && jedis.getbit(BLOOM_FILTER, hash2)
                && jedis.getbit(BLOOM_FILTER, hash3);
    }
}
